package com.wjpeng.wms.service.impl;

import com.wjpeng.wms.domain.Role;
import com.wjpeng.wms.mapper.RoleMapper;
import com.wjpeng.wms.query.QueryObject;
import com.wjpeng.wms.service.IRoleService;
import com.wjpeng.wms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void saveOrUpdate(Role d, Long[] permissionIds, Long[] menuIds) {
        if(d.getId() == null){
            roleMapper.insert(d);
        }else{
            roleMapper.deleteReation(d.getId());//先打破维护关系
            roleMapper.deleteMenusReation(d.getId());//先打破维护关系
            roleMapper.updateByPrimaryKey(d);//然后再执行更新语句
        }

        //无论是插入语句还是更新语句,如果传入的权限参数不为空,都要建立角色和权限的维护关系
        if(permissionIds != null){
            for (Long permissionId : permissionIds) {
                roleMapper.insertReation(d.getId(),permissionId);
            }
        }

        if(menuIds != null){
            for (Long menuId : menuIds) {
                roleMapper.insertMenusReation(d.getId(),menuId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        if(id != null){
            roleMapper.deleteReation(id);//先打破维护关系
            roleMapper.deleteMenusReation(id);//先打破维护关系
            roleMapper.deleteByPrimaryKey(id);//然后再执行删除语句
        }
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult result(QueryObject qo) {
        Integer count = roleMapper.queryCount(qo);
        if(count == 0){
            return new PageResult(Collections.EMPTY_LIST,0,1,0);
        }
        return new PageResult(roleMapper.queryLimit(qo),count,qo.getCurrentPage(),qo.getPageSize());
    }
}
